import {MangaSite} from "../MangaSite";
import {parseXML, reduceHTML2SimpleXML, StXML} from "../../../function/xmlFunc";
import { writeFile} from "../../../function/fileFunc";
import {ManHuaDui} from "../ManHuaDui/ManHuaDui";
import {requestText} from "../../../function/httpFunc";
declare const arr_pages: string[];
declare const g_chapter_id: string;
declare const g_comic_id: string;
export namespace DMZJ {
    export interface ImgItemInfo extends  MangaSite.ImgItemInfo {
    }
    export interface TravelBaseNode extends StXML.BaseNode {
        traveled: boolean;
        children: TravelNode[];
    }
    export interface TravelTextNode extends StXML.TextNode {
        traveled: boolean;
    }
    export type TravelNode = TravelBaseNode | TravelTextNode;
}

export class DMZJ extends MangaSite {
    public readonly imgPrefix: string = "https://images.dmzj.com/";
    protected chapterId: string;
    protected comicId: string;
    protected chapterImgList: string[];
    public drawPage(img: HTMLImageElement, position?: "left" | "right", showPageIndexLen?: number): this {
        return this.directDrawPage(img, position);
    }
    public async getImgList(): Promise<MangaSite.ImgItemInfo[]> {
        console.log("get img list");
        const data = await this.getJSON();
        return JSON.parse(data) as ManHuaDui.ImgItemInfo[];
    }
    protected async cacheArticleInfoJSONFile(filename: string): Promise<string> {
        const info = this.articleInfo;
        await this.buildListReferNet(info);
        const imgList: ManHuaDui.ImgItemInfo[] = this.chapterImgList.map((imgUrl: string, imgIndex: number) => {
            return {
                imgIndex: imgIndex + 1,
                type: "DMZJ",
                src: imgUrl,
            };
        });
        const data = JSON.stringify(imgList);
        writeFile(filename, data);
        return Promise.resolve(data);
    }
    protected async buildListReferNet(articleInfo: MangaSite.IArticleBaseInfo) {
        console.log("build list refer net");
        const html = await requestText(articleInfo.origin_url);
        const xml = reduceHTML2SimpleXML(html);
        const node = parseXML(xml);
        const mainScript = this.getScriptListInfoFromHTML(node);
        this.runMainScript(mainScript);
    }
    protected runMainScript(text: string) {
        window.eval(text);
        const { imgPrefix } = this;
        this.chapterImgList = arr_pages.map((url: string) => {
            return  imgPrefix + decodeURIComponent(url);
        });
        this.chapterId = g_chapter_id;
        this.comicId = g_comic_id;
    }
    protected getScriptListInfoFromHTML(rootNode: StXML.BaseNode): string {
        let nowNode: ManHuaDui.TravelNode = rootNode as DMZJ.TravelBaseNode;
        console.log(rootNode);
        let targetScript: DMZJ.TravelBaseNode;
        nowNode.traveled = true;
        while (true) {
            if (nowNode.isText) {
                const textNode = nowNode as DMZJ.TravelTextNode;
                textNode.traveled = true;
                nowNode = textNode.parent as DMZJ.TravelBaseNode;
            } else {
                const baseNode = nowNode as DMZJ.TravelBaseNode;
                baseNode.traveled = true;
                if (
                    this.isTargetScriptNode(baseNode)
                ) {
                    targetScript = baseNode;
                }
                nowNode = baseNode.children.find((childNode) => !childNode.traveled) as ManHuaDui.TravelNode;
                if (nowNode == null) {
                    if (baseNode.parent == null) {
                        break;
                    }
                    nowNode = baseNode.parent as ManHuaDui.TravelNode;
                }
            }
        }
        return targetScript.children.map((childNode: DMZJ.TravelNode) => {
            const textNode = childNode as DMZJ.TravelTextNode;
            return textNode.text;
        }).join("");
    }
    protected isTargetScriptNode(baseNode: DMZJ.TravelBaseNode): boolean {
        return baseNode.tagName.toLowerCase() === "script" &&
        baseNode.children.length &&
        baseNode.children.some((childNode: DMZJ.TravelNode) => {
            const textNode = childNode as DMZJ.TravelTextNode;
            return textNode.text.indexOf("chapter_id =") > 0;
        });
    }
    protected buildImgReqURL(imgInfo: MangaSite.ImgItemInfo) {
        return super.buildImgReqURL(imgInfo) + "&header_refer=" + encodeURIComponent(this.articleInfo.origin_url);
    }
}
